package me.shurufa.fragments;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.adapter.CatalogAdapter;
import me.shurufa.adapter.CatalogNoNumAdapter;
import me.shurufa.model.BookInfo;
import me.shurufa.model.BookInfoResponse;
import me.shurufa.model.CatalogListResponse;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.NetworkConstants;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.widget.CommentHeader;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import me.shurufa.widget.recyclerview.RecyclerViewUtils;

/**
 * 点击查看目录跳转页面中的目录列表 上部分为书的信息 下部分为fragment
 * 进入直接刷新 不进行自动刷新 不要书摘数目
 * Adapter 与holder 与其他目录列表不同
 *
 * @FileName: me.shurufa.fragments.CatalogNoDigestNumFragment.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-02-02 16:46
 */
public class CatalogNoDigestNumFragment extends BaseListFragment implements View.OnClickListener {
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_refresh)
    PtrClassicFrameLayout ptrRefresh;

    ImageView bookImg;
    TextView bookTitle;
    TextView bookAuthor;
    TextView bookPress;
    View divider;
    TextView watchAllDigest;

    public BookInfo bookInfo;

    CatalogNoNumAdapter catalogAdapter;
    ArrayList dataList;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter = null;

    private long bookId;
    private View headerView;

    public static CatalogNoDigestNumFragment newInstance(long bookId) {
        CatalogNoDigestNumFragment fragment = new CatalogNoDigestNumFragment();
        Bundle args = new Bundle();
        args.putLong(Constants.ARG_BOOK_ID, bookId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            bookId = getArguments().getLong(Constants.ARG_BOOK_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_catalog_list, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
//        初始化刷新
        setRefresh();
        dataList = new ArrayList();
        catalogAdapter = new CatalogNoNumAdapter(this,dataList);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(catalogAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        initHeader();
        RecyclerViewUtils.setHeaderView(recyclerView, headerView);
        recyclerView.addOnScrollListener(mOnScrollListener);
    }

    private void initHeader() {
        headerView = LayoutInflater.from(getActivity()).inflate(R.layout.header_catalog,recyclerView,false);
        watchAllDigest = (TextView) headerView.findViewById(R.id.watch_all_digest);
        bookImg = (ImageView)headerView.findViewById(R.id.book_img);
        bookAuthor = (TextView) headerView.findViewById(R.id.book_author);
        bookTitle = (TextView) headerView.findViewById(R.id.book_title);
        bookPress = (TextView) headerView.findViewById(R.id.book_press);
        watchAllDigest.setOnClickListener(this);
        if (bookInfo!=null){
            if (!TextUtils.isEmpty(bookInfo.image))
                Glide.with(getActivity()).load(bookInfo.image).into(bookImg);
            if (!TextUtils.isEmpty(bookInfo.author))
                bookAuthor.setText(bookInfo.author);
            if (!TextUtils.isEmpty(bookInfo.title))
                bookTitle.setText(bookInfo.title);
            if (!TextUtils.isEmpty(bookInfo.publisher))
                bookPress.setText(bookInfo.publisher);
        }else {
            new RequestServerTask<BookInfoResponse>(BookInfoResponse.class) {
                @Override
                protected String requestServer() {
                    Map<String, Object> params = new HashMap<>();
                    params.put("bookId", bookId);
                    return HttpUtil.post(NetworkConstants.GET_BOOK_INFO, params);
                }

                @Override
                protected void onSuccess(BookInfoResponse result) {
                    if (!TextUtils.isEmpty(result.data.image))
                        Glide.with(getActivity()).load(result.data.image).into(bookImg);
                    if (!TextUtils.isEmpty(result.data.author))
                        bookAuthor.setText(result.data.author);
                    if (!TextUtils.isEmpty(result.data.title))
                        bookTitle.setText(result.data.title);
                    if (!TextUtils.isEmpty(result.data.publisher))
                        bookPress.setText(result.data.publisher);
                }
            }.start();
        }
    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);

            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView);
            if(state == LoadingFooter.State.Loading) {
                LogUtils.kLog().e("the state is Loading, just wait..");
                return;
            }

            if (hasMore) {
                // loading more
                RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, 10, LoadingFooter.State.Loading, null);
                loadData(mPage);
            } else {
                //the end
                RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, 10, LoadingFooter.State.TheEnd, null);
            }
        }
    };

    private void setRefresh() {
        ptrRefresh.setResistance(4.2F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(300);
        ptrRefresh.setDurationToCloseHeader(1000);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                boolean canbePullDown = PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view1);
                return canbePullDown;
            }
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        自动刷新一次
//        ptrRefresh.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                ptrRefresh.autoRefresh(true);
//            }
//        }, 400);
        refresh();
    }

    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {
        CatalogListResponse resp = (CatalogListResponse) response;
        if (isNew) {
            catalogAdapter.clear();
        }
        catalogAdapter.append(resp.data);
        catalogAdapter.notifyDataSetChanged();
    }

    @Override
    protected void showEmptyView() {

    }

    @Override
    protected void hideEmptyView() {

    }

    @Override
    protected void setHasMore(boolean hasMore) {

    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, CatalogListResponse.class);
    }

    @Override
    public void refresh() {
        super.refresh();
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ptrRefresh!=null&&ptrRefresh.isRefreshing()) {
                    ptrRefresh.refreshComplete();
                }
            }
        },2000);
        onRefresh();
    }

    public void onRefresh() {
        mPage=1;
        loadData(1);
    }

    private int mPage;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, 10, LoadingFooter.State.Loading, null);
            loadData(mPage);
        }
    };


    protected void loadData(final int page) {
        if (!NetworkUtils.isNetAvailable(getActivity())){
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, 10, LoadingFooter.State.NetWorkError, this.mFooterClick);
        }else {
            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Loading);
            new RequestServerTask<CatalogListResponse>(CatalogListResponse.class) {
                @Override
                protected String requestServer() {
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("bookId",bookId);
                    params.put("page",page);
                    LogUtils.kLog().e("page="+page);
                    return HttpUtil.post(NetworkConstants.GET_BOOK_MENU, params);
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    endRefreshing();
                }


                //                ////////////////Notice！！ 目前目录是一次性全部加载 所以不算分页 加载成功后直接设置已全部加载
                @Override
                protected void onSuccess(CatalogListResponse result) {
                    //没有更多数据 不能加载更多
                    if (result.data == null || result.data.length == 0) {
                        hasMore = false;
                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);
                    } else {
//                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);
                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);
//                        hasMore = true;
                        hasMore = false;
                        mPage++;
                        bindData(result, page == 1);
                    }
                }
            }.start();
        }
    }

    public void endRefreshing() {
        if (ptrRefresh != null) {
            ptrRefresh.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ptrRefresh!=null) {
                        ptrRefresh.refreshComplete();
                    }
                }
            }, 500);
        }
    }

    @Override
    public void onClick(View v) {

    }
}
